﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GameView.Comment;
using GameView.Services;
using GameView.Services.Comment;
using GameView.Services.Dtos.GameLoginDto;
using GameView.Services.Dtos.Project;
using System.Collections.ObjectModel;
using System.Windows.Controls;

namespace GameView.ViewModels
{
    public partial class GameLoginViewModel : ObservableObject
    {
        private List<ProjectWithGamesInfo> pgs = [];
        private readonly ProjectService _proService;
        private readonly GameLoginService _service;

        public GameLoginViewModel(GameLoginService service, ProjectService pservice)
        {
            _service = service;
            _proService = pservice;
            LoadData().ConfigureAwait(false);
        }
        [ObservableProperty]
        private bool _isLoading = false;
        [ObservableProperty]
        private int _pageIndex = 1;
        [ObservableProperty]
        private int _pageSize = 50;
        [ObservableProperty]
        private int _totalCount = 0;
        [ObservableProperty]
        private int _totalPages = 1;
        [ObservableProperty]
        private bool _hasPrevPages = false;
        [ObservableProperty]
        private int _pageNumber = 0;
        [ObservableProperty]
        private string _selectedGame;
        [ObservableProperty]
        private ObservableCollection<string> _projectOptions = [];
        [ObservableProperty]
        [NotifyPropertyChangedFor(nameof(GameOptions))]
        private string _selectedProject;
        [ObservableProperty]
        private ObservableCollection<string> _gameOptions = [];
        [ObservableProperty]
        private bool _hasNextPages = true;
        [ObservableProperty]
        private ObservableCollection<GameLoginEntity> _gameLoginRecords = [];
        [ObservableProperty]
        private GameLoginQueryDto _queryDto = new();

        [RelayCommand]
        private async Task FirstPage()
        {
            PageIndex = 1;
            PageNumber = 1;
            await LoadFromApi();
        }

        [RelayCommand]
        private async Task PreviousPageAsync()
        {
            PageIndex--;
            PageNumber--;
            HasPrevPages = PageIndex > 1;
            await LoadFromApi();
        }

        [RelayCommand]
        private async Task NextPageAsync()
        {
            PageIndex++;
            PageNumber++;
            await LoadFromApi();
        }

        [RelayCommand]
        private void LastPage() => PageIndex = TotalPages;

        [RelayCommand]
        private async Task ChangePageSize(object size)
        {
            ComboBoxItem cb = (ComboBoxItem)size;
            if (cb.Content is string sizeStr && int.TryParse(sizeStr.Replace("条/页", ""), out var newSize))
            {
                PageSize = newSize;
                PageIndex = 1; // 重置到第一页
                await LoadFromApi();
            }
        }

        [RelayCommand]
        private async Task SearchAsync()
        {
            IsLoading = true;
            await Task.Delay(200);
            try
            {
                PageIndex = 1;
                await LoadFromApi();
            }
            catch (Exception ex)
            {
                GlobalMessage.Instance.ShowError($"数据加载错误：{ex.Message}");
            }
            finally
            { IsLoading = false; }
        }

        [RelayCommand]
        private async Task LoadData()
        {
            IsLoading = true;
            await LoadFromApi();
            var res = await _proService.GetAllAsync();
            pgs = res.Data;
            ProjectOptions.Clear();
            GameOptions.Clear();
            pgs ??= [];
            foreach (var data in pgs)
            {
                ProjectOptions.Add(data.Name);
            }
            if (pgs.Count >= 1)
            {
                foreach (var item in pgs.First().Games)
                    GameOptions.Add(item.Name);
            }
            IsLoading = false;
        }
        private async Task LoadFromApi()
        {
            IsLoading = true;
            await Task.Delay(200);
            try
            {
                QueryDto.PageIndex = PageIndex;
                QueryDto.PageSize = PageSize;
                QueryDto.ProjectName = SelectedProject;
                QueryDto.GameName = SelectedGame;
                var res = await _service.GetPageAsync(QueryDto);
                if (res.StatusCode != 200)
                {
                    GlobalMessage.Instance.ShowError(JSON.Serialize(res.Errors));
                    return;
                }
                PageSize = res.Data.PageSize;
                TotalPages = res.Data.TotalPages;
                TotalCount = res.Data.TotalCount;
                HasNextPages = res.Data.HasNextPages;
                HasPrevPages = res.Data.HasPrevPages;
                PageIndex = res.Data.PageIndex;
                GameLoginRecords.Clear();
                if (res.Data.Items == null)
                    return;
                foreach (var rr in res.Data.Items)
                {
                    GameLoginRecords.Add(rr);
                }
            }
            catch (Exception ex)
            {
                GlobalMessage.Instance.ShowError($"数据加载错误：{ex.Message}");
            }
            finally
            { IsLoading = false; }
        }
        partial void OnSelectedProjectChanged(string value)
        {
            // 清空游戏选项
            GameOptions.Clear();
            // 根据选择的项目重新加载游戏选项
            if (!string.IsNullOrEmpty(value))
            {
                var nowProjet = pgs.FirstOrDefault(q => q.Name == SelectedProject);
                if (nowProjet == null || nowProjet.Games.IsNullOrEmpty())
                    return;
                foreach (var game in nowProjet.Games)
                {
                    GameOptions.Add(game.Name);
                }
            }
        }
    }
}